import { ISubmitOrderResult } from "../model/order";
import tools from "../common/tools";
import wxService from "../common/wxService";
import utils from "./utils";
import { config } from "../etc/config";
import httpClient from "../common/http-client";


class OrderHelper {
	constructor() {
	}
	currUser = function () {
		const user = wx.getStorageSync("userInfo");
		return user;
	}

	Pay(orderId: string, formId?: string, paySuccessCallBack?) {
		return httpClient.post<ISubmitOrderResult>(config.order.order_pay_apply_wx, { id: orderId })
			.then(res => {
				if (res.succeed) {
					res.value.orderId = orderId;
					this.wxPayment(res.value, formId, (pres) => {
						utils.showToastText('支付已取消');
					}, paySuccessCallBack);
				} else {
					wxService.showToast(res.msg);
				}
			}).catch(e => {
				console.log('payerror：' + e);
			});
	}

	wxPayment(data: ISubmitOrderResult, formId: string, payFinlcallback?, paySuccessCallBack?) {		
		wx.requestPayment({
			package: data.package,
			nonceStr: data.nonceStr,
			timeStamp: data.timeStamp.toString(),
			signType: data.signType,
			paySign: data.paySign,
			//complete: callback
			complete: (res) => {
				if (res.errMsg === 'requestPayment:cancel' || res.errMsg === 'requestPayment:fail cancel') {
					if (payFinlcallback && typeof (payFinlcallback) == "function") {
						payFinlcallback(res);
					}
				} else {
					if (paySuccessCallBack && typeof (paySuccessCallBack) == "function") {
						if (formId) {
							this.notify(data.orderId, formId);
						}
						paySuccessCallBack(res);
					} else {
						wxService.navigateTo(tools.buildUrl('/pages/payment/success/index', { id: data.orderId }));
					}
				}
			}
		});
	}

	private notify(orderId: string, formId: string) {
		const user = wx.getStorageSync("userInfo");
		if(!user || !user.openId){
			return;
		}
		httpClient.get<ISubmitOrderResult>(tools.buildUrl(config.notify.notify_bysuccess_wx, { openId: user.openId, formId: formId, orderId: orderId }))
			.then(res => {
				console.log('发送完毕');

			}).catch(e => {

				console.log('通知出错:' + e);
			})
	}

}

export default new OrderHelper();